package xyc.szk.web.servlet.session;
/*
 * @Description:
 * @Author: 山志凯
 * @Date: 2021-04-14
 * @Time: 09:22
 */

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCode")
public class CheckCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //产生验证码
        //1、生成一个图片：这个图片是放在内存中的
        int width=60;
        int height=30;
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //2、给图片加上验证码：数字，字母 ,给图片作修饰
        String numbers="0123456789";
        Random rd = new Random();
        Graphics g = bufferedImage.getGraphics();//获取图片的画笔
        g.setColor(new Color(250,120,130));
        g.fillRect(0,0,width,height);

        g.setColor(new Color(100,123,200));


        StringBuilder sb=new StringBuilder();
        int index = rd.nextInt(10);//随机索引号
        char ch=numbers.charAt(index);
        g.drawString(ch+"",5,18);
        sb.append(ch);

        index = rd.nextInt(10);//随机索引号
        ch=numbers.charAt(index);
        g.drawString(ch+"",15,20);
        sb.append(ch);

        index = rd.nextInt(10);//随机索引号
        ch=numbers.charAt(index);
        g.drawString(ch+"",30,22);
        sb.append(ch);

        index = rd.nextInt(10);//随机索引号
        ch=numbers.charAt(index);
        g.drawString(ch+"",40,20);
        sb.append(ch);
        //将验证娄字存入到 session
        HttpSession session = req.getSession();
        session.setAttribute("code",sb.toString());

        //3、将图片响应给浏览器端
        ServletOutputStream out = resp.getOutputStream();//获取 字节 流
        ImageIO.write(bufferedImage,"jpeg",  out); //将图片发送到浏览器上
        g.dispose();
    }
}

